#!/usr/bin/env ruby
#-*- coding:utf-8 -*-

require "date"
require "base64"
require 'chilkat'


def decode_quoted_printable str, charset
  crypt = Chilkat::CkCrypt2.new()
  #  Any string argument automatically begins the 30-day trial.
  success = crypt.UnlockComponent("30-day trial")
  if (success != true)
      print crypt.lastErrorText() + "\n";
      return nil
  end
  crypt.put_CryptAlgorithm("none")
  crypt.put_EncodingMode("quoted-printable")
  crypt.put_Charset(charset)
  crypt.decryptStringENC(str)
end


class POP3Parse
  attr_reader :data, :charset, :date, :subject, :mail_from, :mail_to, :body
  def initialize content
    parse content
  end
  def parse content
    @data = {"body" => ""}
    last_key = nil
    has_newline = false
    header_over = false
    content.each_line do |line|
      if !header_over && line.match(/^\s/) then
        if line == "\r\n" || line == "\n" then        # 头是否结束
          if !has_newline then
            has_newline = true
          else
            header_over = true
          end
        elsif last_key then
          @data[last_key] += line
        end
      elsif !header_over then
        entry = line.split ": "
        last_key = entry[0].strip
        @data[last_key] = entry[1]
      else
        @data["body"] += line
      end
    end
    @date = DateTime.parse @data["Date"]
    @mail_from = @data['From'].strip
    @mail_to = @data['To'].strip
    subject = []
    @data["Subject"].each_line do |line|
      sub = line.strip[2..-3].split("?")
      @charset = sub[0]
      subject.push Base64.decode64(sub[-1]).encode "UTF-8", sub[0]
    end
    @subject = subject.join " "
    @body = decode_quoted_printable @data['body'], @charset

    @data
  end
end


if caller.length == 0
  h = POP3Parse.new File.read('163_1')
  puts h.date
  #puts h.transfer_encoding
  puts h.mail_from
  puts h.mail_to
  puts h.subject
  puts h.body
end
